package com.yuma.tingshu.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.yuma.tingshu.model.live.SocketMsg;
import jakarta.websocket.Session;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class LiveRoomContainer {
    //存储一个直播间和它的用户的对应关系
    //4: 1  2  24  36
    //5: 1  9  24  90 为了避免一个人重复的进入直播间，将List变成Set
    private static Map<Long, Set<Long>> roomMap = new ConcurrentHashMap<>();
    // 1:  Session1
    // 2:  Session2
    //24：Session24
    private static Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    public static void join(Long roomId, Long userId, Session session) {
        //获取当前直播间用户列表
        Set<Long> userIdSet = roomMap.get(roomId);
        //如果是第一个人，应该创建value Set，建立Map的一个key-value
        if (userIdSet == null) {
            userIdSet = new HashSet<>();
            roomMap.put(roomId, userIdSet);
        }
        //将userId加入Set
        userIdSet.add(userId);

        //将用户id和用户的session建立映射
        sessionMap.put(userId, session);
    }

    public static void leave(Long roomId, Long userId, Session session) {
        //从roomMap去除自己
        Set<Long> userIdSet = roomMap.get(roomId);
        if (userIdSet != null) {
            userIdSet.remove(userId);
        }
        //sessionMap去除自己的session
        sessionMap.remove(userId);
    }

    //群发
    public static void sendMessage(SocketMsg socketMsg) {
        //MSG不能为空
        if (socketMsg == null) {
            return;
        }
        if (SocketMsg.MsgTypeEnum.HEART_BEAT.getCode().equals(socketMsg.getMsgType()) &&
                SocketMsg.MsgTypeEnum.TOKEN_INVALID.getCode().equals(socketMsg.getMsgType())) {
            return;
        }
        //获取当前直播间的所有userId
        Set<Long> userIdSet = roomMap.get(socketMsg.getLiveRoomId());

        if (CollectionUtils.isNotEmpty(userIdSet)) {
            userIdSet.forEach(userId -> {
                //根据每个userId获取它的session
                Session session = sessionMap.get(userId);
                //调用session发送数据
                session.getAsyncRemote().sendText(JSON.toJSONString(socketMsg));
            });
        }

    }
}
